import http from '@ohos.net.http'
import router from '@ohos.router'
import promptAction from '@ohos.promptAction'
import { LoginResult } from '../types/member'
import { Data } from '../types/Comm'

const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

export const ht2 = <T>(url: string, options?: http.HttpRequestOptions): Promise<Data<T>> => {
  if (!url.startsWith('http')) {
    url = baseURL + url
  }

  options.header = {
    ...options.header,
    'source-client': "miniapp"
  }

  let memberStore: LoginResult = AppStorage.Get("memberStore")
  const token = memberStore?.token
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': token
    }
  }

  console.log("请求头信息：" + JSON.stringify(options))
  return new Promise<Data<T>>((resolve, reject) => {
    http.createHttp().request(url, options).then(res => {
      if (res.responseCode >= 200 && res.responseCode <= 300) {
        resolve(JSON.parse(res.result as string))
      } else if (res.responseCode === 401) {
        AppStorage.Delete("memberStore")
        router.pushUrl({
          url: 'pages/Login'
        })
        reject(res)
      } else {
        promptAction.showToast({
          message: JSON.parse(res.result as string).msg || '请求错误！'
        })
        reject(res)
      }
    }).catch(err => {
      promptAction.showToast({
        message: err ? JSON.stringify(err) : '网络错误！',
        duration: 3000
      })
      reject(err)
    })
  })
}
